function rotate(matrix, direction) {
    return direction === 'clockwise' ?
        matrix[0].map((_, i, origin) => matrix.map(a => a[i]).reverse()) :
        matrix[0].map((_, i, origin) => matrix.map(a => a[i])).reverse()
}
function validateBattlefield(field) {
    var rules = { 1: 4, 2: 3, 3: 2, 4: 1 }
    var counts = { 1: 0, 2: 0, 3: 0, 4: 0 }
    function is_diagonal_contact(i, j) {
        var diff = [[-1, -1], [-1, 1], [1, -1], [1, 1]];
        for (d of diff) {
            var [row, col] = [i + d[0], j + d[1]];
            if (row > -1 && row < field.length && col > -1 && col < field[0].length) if (field[row][col]) return true;
        }
        return false;
    }

    for (var i = 0; i < field.length; i++) {
        for (var j = 0; j < field[0].length; j++) {
            if (field[i][j]) {
                //invalid shape
                if ((i + 1 < field.length && field[i + 1][j]) || (i - 1 > -1 && field[i - 1][j])) if (field[i][j + 1] || field[i][j - 1]) { console.log('invalid shape'); return false; }
                //check for diagonal contact
                if (is_diagonal_contact(i, j)) return false;
                //sing cell as 1
                if ((i - 1 > -1 && field[i - 1][j] === 0) && (i + 1 < field.length && field[i + 1][j] === 0) && (j - 1 > -1 && field[i][j - 1] === 0) && (j + 1 < field[0].length && field[i][j + 1] === 0)) counts[1]++;
            }
        }
    }

    for (x of field.map(v => v.join(''))) {
        var temp = x.match(/1{2,}/g) || [];
        for (y of temp) counts[y.length]++;
    }
    for (x of rotate(field).map(v => v.join(''))) {
        var temp = x.match(/1{2,}/g) || [];
        for (y of temp) counts[y.length]++;
    }
    for (x of Object.keys(counts)) {
        if (counts[x] != rules[x]) return false
    }
    return true
}
